<?php
namespace DataWidgetTp\utility;

use DataWidget\contract\FilterHandler;
use think\db\Query;
use DateTime;

/**
 * Query的装饰器类，可以调用Query的所有方法
 */
class QueryFilterHandler implements FilterHandler
{
    /** @var Query */
    protected $query;
    public function __construct($query)
    {
        $this->query = $query;
    }
    /** @return QueryFilterHandlerPseudo */
    static public function decorate($query)
    {
        return new static($query);
    }
    public function __get($name)
    {
        return $this->query->$name;
    }
    public function __call($name, $arguments)
    {
        return call_user_func_array([$this->query, $name], $arguments);
    }
    public function filter($method, $field, $condition)
    {
        if(method_exists($this,$method)){
            return call_user_func([$this, $method], $field, $condition);
        }
    }
    public function equal($field,$condition)
    {
        $this->query->where([$field => $condition]);
    }
    public function like($field,$condition)
    {
        $fields=explode(",",$field);
        foreach($fields as $field){
            $this->query->whereLike($field,"%$condition%","OR");
        }
    }
    public function date($field,$condition)
    {
        $dt=new DateTime();
        $dt->setTimestamp($condition);
        if($dt){
            $start=$dt->setTime(0,0,0)->getTimestamp();
            $end=$dt->setTime(24,0,0)->getTimestamp();
            $this->query->whereBetween($field, [$start, $end]);
        }
    }
    public function between($field,$condition)
    {
        if($condition["start"]) $this->after($field,$condition["start"]);
        if($condition["end"]) $this->before($field,$condition["end"]);
    }
    public function after($field,$condition)
    {
        $dt=date_create_from_format("Y-m-d H:i:s",$condition);
        if($dt){
            $condition=$dt->getTimestamp();
            $this->query->where($field, ">", $condition);
        }
    }
    public function before($field,$condition)
    {
        $dt=date_create_from_format("Y-m-d H:i:s",$condition);
        if($dt){
            $condition=$dt->getTimestamp();
            $this->query->where($field, "<", $condition);
        }
    }
}
